from django.template.loader import render_to_string
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponse
from models import Country
import simplejson

# Create your views here.
def get_normalized_region(country, region):
    return dict(region_codes(country))[region]

def region_codes(country):
    country = get_object_or_404(Country, iso=country.upper())
    if country.region_module:
        imp = __import__(country.region_module, globals(), locals(), [country.region_choices], -1)
        return getattr(imp, country.region_choices)
    elif len(country.regionentry_set.all()):
        return [(region['code'], region['name']) for region in country.regionentry_set.all().values('name', 'code')]
    return None

def get_region_codes(request, country):
    codes = region_codes(country)
    if codes is not None:
        return HttpResponse(simplejson.dumps({'html':render_to_string("countries/region_codes.html",{'regions':codes}),
                                              'type':'select'}))
    return HttpResponse(simplejson.dumps({'type':'text'}))
